package com.yx.memcache;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClient;

public final class MemcachedManager {
	private List<CachedServer> servers;
	private MemcachedClient memClient;
	protected static final int DEFAULT_TIMEOUT=3;
	protected static final  TimeUnit DEFAULT_TIMEUNIT=TimeUnit.SECONDS;
	private static MemcachedManager instance=null;
	private MemcachedManager(List<CachedServer> servers)throws Exception {
		this.servers = servers;
	}
	public static void init(String[] serverIpAndPort)throws Exception{
		List<CachedServer> serversList=new ArrayList<CachedServer>();
		for (int i = 0; i < serverIpAndPort.length; i++) {
			String address = serverIpAndPort[i];
			String ip = address.substring(0, address.indexOf(":"));
			int port = Integer.parseInt(address.substring(address.indexOf(":") + 1));
			serversList.add(new CachedServer(ip, port));
		}
		if(instance==null){
			instance=new MemcachedManager(serversList);
			instance.connect();
		}
	}
	public static Cached get()throws Exception{
		if(instance.memClient!=null){
			return new Cached(instance.memClient);
		}else{
			throw new Exception("Memcached is not alive");
		}
	}

	private void connect() throws IOException {
		if (memClient != null) {
			return;
		}
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < servers.size(); i++) {
			CachedServer server = servers.get(i);
			buf.append(server.toString()).append(" ");
		}
		memClient = new MemcachedClient(AddrUtil.getAddresses(buf.toString()));
	}

	
}
